<template>
 <el-container class="home-container">

  <!-- 导航框 -->

   <div class="cart">

  <el-breadcrumb separator="/">
           <el-breadcrumb-item :to="{ path: '/index' }">首页</el-breadcrumb-item>
           <el-breadcrumb-item>购物车</el-breadcrumb-item>
         </el-breadcrumb>

    <div class="add">

        <div class="a">
            <div class="b">
          <span>确认收货地址</span>
    </div>

       <div class="c">
         <el-button type="primary" round icon="el-icon-circle-plus" @click="dialogVisible = true">添加新地址</el-button>
         </div>

         </div>

          <el-table
             :data="tabledata1"
              tooltip-effect="dark"
              style="width: 80%" :row-class-name="tableRowClassName"
              ref="multipleTable"
              @select-all="onSelectAll"
               @selection-change="selectItem"
               @row-click="onSelectOp">
              >
               <el-table-column type="selection" width="55" align="center"></el-table-column>
            <el-table-column
              prop="name"
              label="姓名"
              width="180">
            </el-table-column>
              <el-table-column
                prop="telephone"
                label="手机号码"
                width="180">
              </el-table-column>

              <el-table-column
                prop="address"
                label="地址">
              </el-table-column>

               <el-table-column
                label="操作">
                <template slot-scope="scope">
                   <el-button type="primary" icon="el-icon-edit" size="small" @click="updateUserBtn(scope.row)"></el-button>
                   <el-button type="danger" icon="el-icon-delete" size="small" @click="deleteaddr(scope.row)"></el-button>
                </template>
              </el-table-column>
            </el-table>
    </div>

      <el-table
        :data="tableData"
         border
         style="width: 100%"
        @selection-change="handleSelectionChange"
        v-if="tableData.length"
      >
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column type="index" label="商品编号" width="180" align="center"></el-table-column>
       <!--  <el-table-column type="img" prop="images"  label="商品图片展示" width="220" align="center"> -->

         <!-- </el-table-column> -->
         <el-table-column prop="images" label="商品图片展示" width="180"  align="center">
         	<!--加入下面的内容,scope.row代表这一行,img是显示这一行的哪个字段,我的是img,你的自己看下-->
         	 <template slot-scope="scope" >
                       <img :src="scope.row.images" alt="物美价廉" style="width: 50px;height: 50px">
              </template>
         </el-table-column>

        <el-table-column type="name" prop="title"  label="商品名字" width="220" align="center"></el-table-column>

       <el-table-column prop="price" label="单价" align="center" width="100"></el-table-column>

       <el-table-column  prop="number" label="数量" align="center" width="190">

              <template scope="scope">
                 <el-input v-model="scope.row.number" :value="scope.row.number"  @change="changeCount(scope.row)" :min="1" :max="scope.row.num">
                 <el-button slot="prepend" @click="changeQuantity(scope.row,-1)"><i class="el-icon-minus"></i></el-button>
                 <el-button slot="append" @click="changeQuantity(scope.row,1)"><i class="el-icon-plus"></i></el-button>
                  </el-input>

                  </template>

        </el-table-column>
       <el-table-column label="操作" align="center" width="180">
         <template slot-scope="scope">
            <el-button size="mini" type="danger" @click="Delete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

    <div v-else style="text-align: center;">
      购物车里空空如也，快去逛逛吧
    </div>

      <div class="footer">
      <div class="total_warpper">
        <h3>共计：{{totalPrice}}</h3>
        <h3>总数：{{totalNumber}}</h3>
      </div>
      <div class="submit">
       <el-button type="primary" round>提交订单</el-button>
      </div>
</div>
<!-- <button @click="test1">111</button>
<button @click="tijiao">222</button> -->

<el-dialog title="添加用户" :visible.sync="dialogVisible" width="50%" @close="closeDialog">

   <!-- 定义用户提交表单数据 -->
  <el-form :model="addaddress" :rules="rules" ref="addUserRef" label-width="100px" class="demo-ruleForm">
      <el-form-item label="姓名" prop="name">
        <el-input v-model="addaddress.name"></el-input>
      </el-form-item>
      <el-form-item label="电话" prop="telephone">
        <el-input v-model="addaddress.telephone"></el-input>
      </el-form-item>
      <el-form-item label="地址" prop="address">
        <el-input v-model="addaddress.address"></el-input>
      </el-form-item>

    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="addUser">确 定</el-button>
    </span>
  </el-dialog>

 <!-- 定义修改页面 当对话框关闭时,将表格数据重置-->
    <el-dialog title="修改地址" :visible.sync="updateDialogVisible" width="50%" @close="closeUpdateDialog">
      <!-- 定义用户提交表单数据-->
      <el-form :model="updateadd" :rules="rules" ref="updateUserRef" label-width="100px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="updateadd.name" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="telephone">
          <el-input v-model="updateadd.telephone"></el-input>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="updateadd.address"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="updateDialogVisible = false" >取 消</el-button>
        <el-button type="primary" @click="updateUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 定义分页插件-->
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
      :current-page="queryItemInfo.pageNum" :page-sizes="[1, 5, 10, 20]" :page-size="queryItemInfo.pageSize"
      layout="total, sizes, prev, pager, next, jumper" :total="total">
    </el-pagination>
    </div>

</el-container>

  </template>

<script>
export default {
  data () {
    return {
      username: '',
      imgUrl:'../images',

      url: '../../images/good2.jpg',

      deleteUser: {
        username: '',
        goodsId: ''
      },
      // 2.定义分页对象
      queryItemInfo: {
        pageNum: 1,
        pageSize: 10
      },
      goodsList: [],
      idList: [],
      total: 0,

      multipleSelection: [], // 存放已选择的数据

      tableData: [],

      // ----------------------------------------------------------
      dialogVisible: false,
      multipleSelection1: [], // 存放已选择的数据

      addaddress: {
        name: '',
        telephone: '',
        address: ''

      },

      updateDialogVisible: false,
      // 定义修改用户数据封装
      updateadd: {
        name: '',
        telephone: '',
        address: ''
      },

      tabledata1: []

    }
  },
  created () {
    this.username = sessionStorage.getItem('username')// 在登陆页时存储数据，此时取数据
    console.log(this.username)
    this.gettableData(this.username)
    this.getList()
  },
  destroyed() {

      this.changenumber()

  },

  methods: {
    test () {
      console.log(this.goodsList)
    },
    test1 () {


    },



    changeCount (good) {
      this.idList.push(good.id)
      this.idList = Array.from(new Set(this.idList))
    },

    async gettableData (username) {
      const {
        data: result

      } = await this.$http.get('/shopcar/getcar?username=' + username, {
        params: this.queryItemInfo
      })
      if (result.status !== 200) return this.$message.error('获取购物车信息失败!!')
      this.tableData = result.data.rows
      for (var i = 0; i < this.tableData.length; i++) {
       this.tableData[i].images = this.imgUrl + this.tableData[i].images
      }
      this.total = result.data.total
    },


    async Delete (id) {
      // 删除商品分类信息,如果为父级节点则需要删除所有的子级信息
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        // 传递分类id
        const { data: result } = await this.$http.delete('/shopcar/deletegoods', { params: { id: id, username: this.username } })
        if (result.status !== 200) return this.$message.error('删除商品失败')
        this.$message.success('删除商品成功')
        // 删除成功之后,刷新页面数据
        this.gettableData(this.username)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },

    async changenumber () {
      // 修改商品分类信息
      console.log('..............................')
      console.log(this.goodsList)
      console.log(this.username)
      for (let a = 0; a < this.tableData.length; a++) {
        for (let i = 0; i < this.idList.length; i++) {
          if (this.tableData[a].id == this.idList[i]) {
            this.goodsList.push(this.tableData[a])
          }
        }
      }
      console.log(this.goodsList)
      const {
        data: result
      } = await this.$http.put(`/shopcar/updategoods/${this.username}`,this.goodsList)
      if (result.status !== 200) return this.$message.error('更新商品失败')
      console.log('更新商品成功')
    },

    handleSizeChange (pageSize) {
      // console.log("每页展现的条数"+pageSize)
      this.queryInfo.pageSize = pageSize
      this.gettableData(this.username)
    },
    handleCurrentChange (pageNum) {
      // console.log("页数:"+pageNum)
      this.queryInfo.pageNum = pageNum
      this.gettableData(this.username)
    },

    // 商品数量修改
    changeQuantity (row, type) {
      if (type > 0) {
        row.number++
      } else {
        row.number > 1 ? row.number-- : row.number = 1
      }
      console.log(row)
      this.changeCount(row)
    },

    // 点击发生的变化
    handleSelectionChange (val) {
      this.multipleSelection = val // 给定义的数组赋值
    },

    // 地址的js

    tableRowClassName ({ row, rowIndex }) {
      if (rowIndex === 1) {
        return 'warning-row'
      } else if (rowIndex === 3) {
        return 'success-row'
      }
      return ''
    },
    closeDialog () {
      // 重置表格数据
      this.$refs.addUserRef.resetFields()
    },

    onSelectAll () {
      this.$refs.multipleTable1.clearSelection()
    },
    selectItem (rows) {
      if (rows.length > 1) {
        var newRows = rows.filter((it, index) => {
          if (index == rows.length - 1) {
            this.$refs.multipleTable.toggleRowSelection(it, true)
            return true
          } else {
            this.$refs.multipleTable.toggleRowSelection(it, false)
            return false
          }
        })
        this.multipleSelection1 = newRows
      } else {
        this.multipleSelection1 = rows
      }
    },
    onSelectOp (row) {
      this.$refs.multipleTable.clearSelection()
      this.$refs.multipleTable.toggleRowSelection(row, true)
      this.multipleSelection1 = []
      this.multipleSelection1.push(row)
    },

    async getList () {
      const { data: result } = await this.$http.get('/order/list')
      if (result.status !== 200) return this.$message.error('用户收货地址查询失败')
      this.tabledata1 = result.data
    },

    addUser () {
      this.$refs.addUserRef.validate(async valid => {
        // 如果校验失败 则停止数据
        if (!valid) return
        // console.log(this.addUserModel)
        const { data: result } = await this.$http.post('/order/add', this.addaddress)
        if (result.status !== 200) return this.$message.error('地址新增失败')
        this.$message.success('地址新增成功')
        // 关闭对话框
        this.dialogVisible = false
        // 重新获取用户列表
        this.getList()
      })
    },

    async updateUserBtn (user) {
      this.updateDialogVisible = true
      this.updateadd = user
      /* const {data: result} = await this.$http.get("/user/"+user.id)
          if(result.status !== 200) return this.$message.error("用户查询失败")
          this.updateadd = result.data */
    },

    async updateUser () {
      // 1.预校验数据
      // this.$refs.updateUserRef.validate(async valid => {
      //    if(!valid)  return this.$message.error("表单验证没有通过")
      // 根据接口文档要求封装数据
      /* let addr = {}
           addr.name = this.updateadd.name
           addr.telephone = this.updateadd.telephone
           addr.addresses = this.updateadd.addresses */

      const { data: result } = await this.$http.put('/order/updateUser', this.updateadd)

      if (result.status !== 200) return this.$message.error('地址修改失败')
      this.$message.success('用户更新成功')
      this.updateDialogVisible = false
      this.getList()
    },

    async deleteaddr (user) {
      // 1.消息确认框
      const result = await this.$confirm('此操作将永久删除此地址, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(error => error)

      // 如果确认  confirm  如果取消 cancel
      if (result !== 'confirm') {
        return this.$message.info('删除取消')
      }
      const { data: result2 } = await this.$http.delete(`/order/${user.name}`)
      if (result2.status !== 200) return this.$message.error('删除失败')
      this.$message.success('删除成功')
      // 重新加载 数据
      this.getList()
    }

  },

  //  通过computed计算属性及时改变
  computed: {
    // 总价
    totalPrice () {
      var price_total = 0
      for (var i = 0; i < this.multipleSelection.length; i++) {
        price_total +=
           this.multipleSelection[i].price * this.multipleSelection[i].number
      }
      return price_total
    },
    // 总数
    totalNumber () {
      var number_total = 0
      for (var i = 0; i < this.multipleSelection.length; i++) {
        number_total += this.multipleSelection[i].number
      }
      return number_total
    }

  },
  components: {}
}
</script>

 <style scoped>
 .cart {
   margin: 50px auto;
   width: 1300px;
 }
 .group_btn {
   margin-bottom: 30px;
 }
 .addDialog .el-input {
   width: 90%;
 }
 .total_warpper {
  /* text-align: left;
   margin-top: 30px; */
   float: left;
 }
 h3 {
   margin-top: 10px;
 }
 #template{
   display: flex;
   justify-content: space-between;
   align-items: center;
   background-color: red;
 }

 .cell{
       display: flex;
       justify-content: flex-start;
       align-items: center;
 }
.submit{
   /* text-align: right;
    margin-top: 30px; */
    float: right;
}
.footer{
  width: 900px;

}

/* -------------------- */

 .el-table .warning-row {
    background: oldlace;
  }

  .el-table .success-row {
    background: #f0f9eb;
  }

  .add {
    margin-left: 100px;

  }

.a {
  margin-left: 30px;
  width: 500px;
}
.b {
float: left;

}
.c {
  margin-left: 50px;
  float: right;
}

 </style>
